import json
import requests
class BaiduApi():
    def __init__(self):
        self.API_KEY = "BrJZPXyol83tVuvGuizOtidj"
        self.SECRET_KEY = "zJrgD8UX35lfE9IctZlPJEUILYsFo3nk"

    def get_access_token(self):
        """
    使用 AK，SK 生成鉴权签名（Access Token）
    :return: access_token，或是None(如果错误)
    """
        url = "https://aip.baidubce.com/oauth/2.0/token"
        params = {"grant_type": "client_credentials", "client_id": self.API_KEY, "client_secret": self.SECRET_KEY}
        return str(requests.post(url, params=params).json().get("access_token"))

    # 身份证验证
    def idcard(self, picurl):
        print(picurl)
        url = "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token=" + self.get_access_token()

        # image 可以通过 get_file_content_as_base64("C:\fakepath\1.png",True) 方法获取
        payload = 'id_card_side=front&url=%s&detect_ps=false&detect_risk=false&detect_quality=false&detect_photo=false&detect_card=false&detect_direction=false' % (
            picurl)
        headers = {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Accept': 'application/json'
        }

        response = requests.request("POST", url, headers=headers, data=payload)
        data = json.loads(response.text)
        if data['words_result']:
            extracted_data = {
                'name': data['words_result'].get('姓名', {}).get('words', ''),
                'gender': data['words_result'].get('性别', {}).get('words', ''),
                'ethnic': data['words_result'].get('民族', {}).get('words', ''),
                'birthday': data['words_result'].get('出生', {}).get('words', ''),
                'address': data['words_result'].get('住址', {}).get('words', ''),
                'id_number': data['words_result'].get('公民身份号码', {}).get('words', '')
            }
            return extracted_data
        return None



    #人脸识别
    def face_detect(self, imagea, imageb):
        MIN_SIMILARITY_SCORE = 75  # 相似度阈值
        MIN_LIVENESS_SCORE = 0.85  # 活体检测阈值
        url = "https://aip.baidubce.com/rest/2.0/face/v3/match?access_token=" + self.get_access_token()

        def get_image_type(img):
            if img.startswith(("http://", "https://")):
                return "URL"
            elif img.startswith("data:image"):
                return "BASE64"
            else:
                raise ValueError("图片格式必须是URL或Base64")

        payload = json.dumps([
            {
                "image": imagea,
                "image_type": get_image_type(imagea),
                "face_field": "quality,liveness"  # 注意字段名是liveness不是liveliness
            },
            {
                "image": imageb,
                "image_type": get_image_type(imageb),
                "face_field": "quality,liveness"
            }
        ], ensure_ascii=False)

        headers = {'Content-Type': 'application/json'}

        try:
            response = requests.post(url, headers=headers, data=payload.encode("utf-8"))
            result = response.json()

            # 错误处理
            if "error_code" in result:
                return {
                    "success": False,
                    "error_msg": result.get("error_msg", "API请求失败"),
                    "raw_data": result
                }

            # 获取比对分数
            score = result.get("result", {}).get("score", 0)

            # 验证分数有效性
            if not isinstance(score, (int, float)) or score < MIN_SIMILARITY_SCORE:
                return {
                    "success": False,
                    "error_msg": f"人脸相似度不足: {score} (要求≥{MIN_SIMILARITY_SCORE})",
                    "raw_data": result
                }

            # 验证活体检测
            liveness = result.get('result', {}).get('liveness', {})
            if liveness.get('livemapscore', 0) < MIN_LIVENESS_SCORE:
                return {
                    "success": False,
                    "error_msg": f"活体检测未通过: {liveness.get('livemapscore')} (要求≥{MIN_LIVENESS_SCORE})",
                    "raw_data": result
                }

            return {
                "success": True,
                "score": score,
                "error_msg": "",
                "raw_data": result
            }

        except Exception as e:
            return {
                "success": False,
                "error_msg": f"请求异常: {str(e)}",
                "raw_data": None
            }

baiduapi = BaiduApi()